package com.lixiaoyao.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.lixiaoyao.reggie.common.BaseContext;
import com.lixiaoyao.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("开始拦截{}",requestURI);
        /**
         * 1.判断请求是否需要拦截
         * 2.判断用户是否登录
         */
        String[] str = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg",
                "/user/loginout",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "/favicon.ico"
        };
        if(doCheckUrl(str, requestURI)){
            log.info("放行{}",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //判断后台用户是否登录
        if(request.getSession().getAttribute("employee")!=null){
            log.info("已登录,当前用户id为：{}",request.getSession().getAttribute("employee"));
            long id = Thread.currentThread().getId();
            log.info("当前线程id为：{}",id);
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }
        //判断移动端用户是否登录
        if(request.getSession().getAttribute("user")!=null){
            log.info("已登录,当前用户id为：{}",request.getSession().getAttribute("user"));
            long id = Thread.currentThread().getId();
            log.info("当前线程id为：{}",id);
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("未登录");
        return;

    }
    public Boolean doCheckUrl(String[] str,String url){
        AntPathMatcher pathMatcher =new AntPathMatcher();
        for (String s : str) {
            boolean match = pathMatcher.match(s, url);
            if(match){
                return true;
            }
        }
        return false;
    }
}
